package com.JavaWeb.filter;

import com.JavaWeb.pojo.User;
import com.JavaWeb.util.Constants;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;


public class sysFilter implements Filter {
    private List excludedUrls;
    public void init(FilterConfig filterConfig) throws ServletException {
        //filterConfig.getInitParameter(参数(key))过滤器配置获取初始参数
        String excludePattern = filterConfig.getInitParameter("excludedUrls");
        excludedUrls = Arrays.asList(excludePattern.split(","));
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String path = request.getServletPath();
        if(excludedUrls.contains(path)){
            // Authenticate the request through LDAP
            System.out.println("Authenticating the request through LDAP");
            chain.doFilter(req,resp);
            return;
        }
        //过滤器，从Session中获取用户
        User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);
        System.out.println(user);
        if(user==null){//移除了或者注销了，或未登录
            response.sendRedirect(request.getContextPath()+"/jsp/error.jsp");
        }
        else{
            chain.doFilter(req,resp);
        }
    }

    public void destroy() {

    }
}
